<?php

class Warehouse extends CI_Controller {

	var $page = "warehouse";
	var $action  = '';

	public function index(){
		$query = $this->db->query("select w.*,
                  (select concat(firstname,' ',lastname) from users u where u.id = w.updatedby) as updatedby,
		          (select concat(firstname,' ',lastname) from users u where u.id = w.createdby) as createdby		
				    from warehouse as w
				    where w.valid = 1 ");
		$data['User'] = "meeee";
		//echo "SET.......".$this->session->userdata('session_id');
		$data['totalRecords'] =  $query->num_rows();
		$this->admin($data,$query);
	}


	public function add(){
		$this->action = 'add';
		$this->index();
	}


	public function edit($id){

		//$this->createLog();
		$this->action = 'edit';
		$query = $this->db->query("select * from warehouse where id = $id and  valid = 1 limit 1" );
		//$row =
		$data['warehouse'] = $query->row();
			
		$query = $this->db->query("select * from warehouse where  valid = 1");
			
		$this->admin($data,$query);
			
	}

	public function save(){

		$name = $_REQUEST['name'];
		$description = $_REQUEST['description'];
		$region = $_REQUEST['region'];
		$city = $_REQUEST['city'];
		$address = $_REQUEST['address'];

		if($this->validateFields() == FALSE){
			$data['errorMessage'] = validation_errors();
			$this->admin($data, null);
			return;
		}
			
		$isUpdate = false;

			
		if(isset($_REQUEST['id']))
		$isUpdate  = true;
			
		if($isUpdate){

			$updatedby = $this->session->userdata('user_id');

			//$updatedon = date( 'y-m-d',time() );

			echo "UPDATE  warehouse SET  name =  '$name',description =  '$description' ,region =  '$region', city =  '$city', address = '$address' ,updatedby=$updatedby ,updatedon =  NOW() WHERE  id =".$_REQUEST['id'];
			$query = $this->db->query("UPDATE  warehouse SET  name =  '$name',description =  '$description' ,region =  '$region', city =  '$city', address = '$address' ,updatedby=$updatedby ,updatedon =  NOW() WHERE  id =".$_REQUEST['id']);


			$this->db->query($query );

			$this->createLog('WAREHOUSE' , 'UPDATED' ,  "Updated warehouse record where id = ".$_REQUEST['id']);

		}

		else{
			$this->db->query("INSERT INTO  warehouse (id ,name ,description,region,city,address".$this->creationFields()."
								  VALUES (NULL ,  '$name',  '$description','$region' , '$city','$address'".$this->creationValues().")");
			$this->createLog('WAREHOUSE' , 'CREATED' ,  "Created a new Warehouse");
		}

		$this->index();

	}


	public function delete($id){

		$data['deleteId'] = $id;
			
		$query = $this->db->query("update warehouse set valid = false  where id = $id limit 1" );
			
		$this->createLog('WAREHOUSE' , 'DELETED' ,  "Deleted warehouse record where id = $id");
			
		$this->index();
			
	}






}
